package com.wuzhipeng.heart.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzhipeng.heart.user.convention.TimeConstants.loginTimeOut;
import com.wuzhipeng.heart.user.convention.errorcode.BaseErrorCode;
import com.wuzhipeng.heart.user.convention.exception.ClientException;
import com.wuzhipeng.heart.user.convention.secret.loginSecret;
import com.wuzhipeng.heart.user.dao.entity.Therapist;
import com.wuzhipeng.heart.user.dao.entity.Users;
import com.wuzhipeng.heart.user.dao.mapper.TherapistMapper;
import com.wuzhipeng.heart.user.dao.mapper.UsersMapper;
import com.wuzhipeng.heart.user.dto.request.registerDTO;
import com.wuzhipeng.heart.user.service.ITherapistService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhipeng
 * @since 2024-12-23
 */
@RequiredArgsConstructor
@Service
public class TherapistServiceImpl extends ServiceImpl<TherapistMapper, Therapist> implements ITherapistService {
    private final loginTimeOut logintimeout;
    private final loginSecret loginsecret;
    private final UsersMapper usersMapper;
    private final RBloomFilter<String> therapistRegisterCachePenetrationBloomFilter;
    @Override
    public void registerTherapist(registerDTO registerDTO) {

        if(therapistRegisterCachePenetrationBloomFilter.contains(registerDTO.getPhone()))
        {
            Therapist therapist = baseMapper.selectOne(Wrappers.lambdaQuery(Therapist.class)
                    .eq(Therapist::getPhone, registerDTO.getPhone()));
            if(therapist != null)
                throw new ClientException("手机号已注册");
        }
        Therapist therapist = BeanUtil.copyProperties(registerDTO, Therapist.class);
        try {
            baseMapper.insert(therapist);
        } catch (Exception e) {
            therapistRegisterCachePenetrationBloomFilter.add(registerDTO.getPhone());
            throw new ClientException("手机号已注册");
        }
        therapistRegisterCachePenetrationBloomFilter.add(registerDTO.getPhone());
    }

    @Override
    public String login(String phone, String password) {
        if (phone == null || phone.isEmpty()) {
            throw new ClientException(BaseErrorCode.PHONE_VERIFY_ERROR);
        }
        if (password == null && !password.isEmpty())
            throw new ClientException(BaseErrorCode.PASSWORD_VERIFY_ERROR);

        LambdaQueryWrapper<Therapist> wrapper = Wrappers.lambdaQuery(Therapist.class)
                .eq(Therapist::getPhone, phone)
                .eq(Therapist::getPassword, password);
        Therapist user = baseMapper.selectOne(wrapper);
        if (user == null)
            throw new ClientException(BaseErrorCode.USER_LOGIN_ERROR);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", user.getPhone());
        map.put("expirationTime", logintimeout.getTime() + System.currentTimeMillis());
        return JWTUtil.createToken(map, loginsecret.getLoginsecret().getBytes());
    }

    @Override
    public Therapist getTherapistByPhone(String phone) {
        LambdaQueryWrapper<Therapist> wrapper = Wrappers.lambdaQuery(Therapist.class)
                .eq(Therapist::getPhone, phone);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public String retrievePassword(String phone, String name, Boolean isClient) {
        Therapist therapist = getTherapistByPhone(phone);
        Users user = usersMapper.selectOne(Wrappers.lambdaQuery(Users.class)
               .eq(Users::getPhone, phone));

        if (isClient) {
            if (user == null)
                throw new ClientException(BaseErrorCode.USER_NOT_EXIST_ERROR);
            if (!name.equals(user.getUsername()))
                throw new ClientException(BaseErrorCode.USER_REAL_NAME_ERROR);
            else {
                return user.getPassword();
            }
        }
        else {
            if (therapist == null)
                throw new ClientException(BaseErrorCode.USER_NOT_EXIST_ERROR);
            if (!name.equals(therapist.getName()))
                throw new ClientException(BaseErrorCode.USER_NOT_EXIST_ERROR);
            else {
                return therapist.getPassword();
            }
        }
    }
}
